<template>
  <el-dialog
    title="审核表单"
    :visible.sync="visible"
    width="800px"
    append-to-body
    :before-close="handleClose"
  >
    <el-form :model="form" size="small" ref="checkform" :rules="checkRules">
      <el-row v-if="checkWay == 'common' && checkstatus == 0">
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude" class="inline-area">
            <el-input
              v-model.number="form.longitude"
              size="small"
              style="width: 160px"
              maxlength="14"
              @input="
                (val) => {
                  this.replaceDigitDeal(val, 7, 'longitude');
                }
              "
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude" class="inline-area2">
            <el-input
              v-model.number="form.latitude"
              size="small"
              style="width: 160px"
              maxlength="14"
              @input="
                (val) => {
                  this.replaceDigitDeal(val, 7, 'latitude');
                }
              "
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="checkWay == 'common' && checkstatus == 0">
        <el-col :span="24" class="mid-area">
          <div ref="mapContainer" id="maps" class="tdtMap"></div>
        </el-col>
      </el-row>
      <el-row
        style="margin-top: 20px"
        v-if="checkWay == 'common' && checkstatus == 0"
      >
        <el-col :span="24">
          <el-form-item label="上级部门" prop="parentId" class="inline-area">
            <CascaderSelect
              :values="form.parentId"
              :varient="'allDept'"
              @input="choseDpet"
              size="small"
            ></CascaderSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="mid-area">
          <el-form-item
            label="审核意见"
            prop="message"
            v-if="checkWay == 'common'"
          >
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="form.message"
              style="width: 520px"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="审核意见"
            prop="comments"
            v-if="checkWay == 'month'"
          >
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="form.comments"
              style="width: 520px"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        size="small"
        type="primary"
        v-if="checkWay == 'month'"
        @click="submit"
      >
        通 过
      </el-button>
      <el-button
        size="small"
        type="danger"
        v-if="checkWay == 'month'"
        plain
        @click="goBack"
      >
        驳 回
      </el-button>
      <el-button
        size="small"
        type="primary"
        v-if="checkWay == 'common'"
        @click="commonSubmit"
      >
        确认{{ checkstatus == 0 ? "通过" : "驳回" }}
      </el-button>
      <el-button size="small" @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { auditInstitution, getAuditmsg } from "@/api/standingbook/common.js";
import { postAudit } from "@/api/standingbook/month.js";
import CascaderSelect from "@/components/Select/CascaderSelect";
import { replaceDigit } from "@/utils/index";
import L from "leaflet";
// import "leaflet-search";
import "leaflet.chinatmsproviders";
export default {
  components: {
    CascaderSelect,
  },
  props: {
    visible: { type: Boolean, default: false, require: true },
    verifyMessage: { type: String, default: null, require: true },
    checkId: { type: Number, default: null, require: true },
    checkWay: { type: String, default: "", require: true },
    checkMonth: { type: String, default: "", require: false },
    // monthEmeterReqVoList: { type: Array, default: () => [], require: false },
    checkstatus: { type: Number, default: 0, require: false }, // 0 通过  1 驳回
    statusFlage: { type: Number, default: 1, require: false }, // common的审核状态 1 区县待审核 2 地市待审核 3 审核成功 5 区县审核失败 6 地市审核失败
  },
  dicts: ["reporting_status"],
  data() {
    return {
      latlangTest: { lat: 29.6608331, lang: 120.4623413 },
      form: {},
      checkRules: {
        latitude: [
          {
            required: null,
            message: "纬度不能为空",
            trigger: ["blur", "change"],
          },
        ],
        longitude: [
          {
            required: null,
            message: "经度不能为空",
            trigger: ["blur", "change"],
          },
        ],
        parentId: [
          { required: null, message: "上级部门不能为空", trigger: "blur" },
        ],
      },
      mapKey: process.env.VUE_APP_MAPKEY,
      imgTeye1: require("@/assets/images/visualization/type (1).png"),
      map: null,
      layers: null,
      latlng: {
        lat: "",
        lng: "",
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        // console.log(this.dict.type.reporting_status);
        if (this.checkWay == "common") {
          this.form = {
            id: "",
            message: "", // 审核意见
            status: null, // 审核状态
            parentId: null, // 父部门ID
            latitude: "", // 纬度
            longitude: "", // 经度
          };
          this.form.id = this.checkId;
          // if (this.verifyMessage != null) {
          //   this.form.message = this.verifyMessage;
          // }
          setTimeout(() => {
            this.Auditmsg();
            if (this.checkstatus == 0 && this.map == null) {
              setTimeout(() => {
                this.getMap(true);
              }, 500);
            }
            if (this.checkstatus == 0) {
              this.rulesRequire(true);
            } else {
              this.rulesRequire(false);
            }
          }, 500);
        } else if (this.checkWay == "month") {
          this.form = {
            id: "",
            comments: "", // 审核意见
            month: "", // 月份
            status: null, // 审核状态 1 通过 0驳回
            // monthEmeterReqVoList: [], // 审核表单数据
          };
          this.form.id = this.checkId;
          if (this.verifyMessage != null) {
            this.form.comments = this.verifyMessage;
          }
          if (this.checkMonth) {
            this.form.month = this.checkMonth;
          }
          // if (this.monthEmeterReqVoList) {
          //   this.form.monthEmeterReqVoList = this.monthEmeterReqVoList;
          // }
        }
      }
    },
  },
  created() {},
  methods: {
    replaceDigitDeal(val, digit, flage) {
      if (val <= 180) {
        this.form[flage] = replaceDigit(val, digit);
      } else {
        this.form[flage] = 180;
      }
    },
    resetData() {
      // this.resetForm("checkform");
      // this.map = null;
      // this.layers = null;
      // this.latlng = {
      //   lat: "",
      //   lng: "",
      // };
    },
    // 月报通过
    submit() {
      switch (this.checkWay) {
        // case "common":
        //   this.form.status = 2;
        //   break;
        case "month":
          this.form.status = 1;
          break;
      }
      this.requestAudit(1);
    },
    // 月报驳回
    goBack() {
      switch (this.checkWay) {
        // case "common":
        //   this.form.status = 3;
        //   break;
        case "month":
          this.form.status = 0;
          break;
      }
      this.requestAudit(2);
    },
    commonSubmit() {
      switch (this.checkstatus) {
        // 通过
        case 0:
          this.form.status = 1;
          this.requestAudit(1);
          break;
        // 驳回
        case 1:
          this.form.status = 0;
          this.requestAudit(2);
          break;
      }
    },
    // rules 必选判断
    rulesRequire(flage) {
      this.checkRules.latitude[0].required = flage;
      this.checkRules.longitude[0].required = flage;
      this.checkRules.parentId[0].required = flage;
    },
    requestAudit(flage) {
      this.$refs["checkform"].validate((valid) => {
        if (valid) {
          let params = { ...this.form };
          if (typeof params.parentId == "object" && flage == 1) {
            if (params.parentId.length > 0) {
              params.parentId = params.parentId[params.parentId.length - 1];
            }
          }
          let requestWay, txt;
          switch (this.checkWay) {
            case "common":
              requestWay = auditInstitution;
              txt = "系统错误,请联系管理员!20038";
              break;
            case "month":
              requestWay = postAudit;
              txt = "系统错误,请联系管理员!20047";
              break;
          }
          // debugger;
          requestWay(params)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              } else {
                if (res.code == 200) {
                  let msg = flage == 1 ? "审核通过" : "驳回成功";
                  this.$message({
                    message: msg,
                    type: "success",
                  });
                  this.handleClose();
                  if (this.checkWay == "common") {
                    this.$parent.handleClose(true);
                  } else if (this.checkWay == "month") {
                    // 重新查询该ID的月报刷新状态
                    this.$parent.handleQuery();
                  }
                }
              }
            })
            .catch((err) => {
              this.$message.error(txt);
            });
        }
      });
    },
    handleClose() {
      this.resetData();
      // this.chinaLayers();
      // this.clearLayers();
      this.$emit("update:visible", false);
    },
    getDept() {
      listDept()
        .then((res) => {})
        .catch((err) => {});
    },
    // 获取上级审核的信息
    Auditmsg() {
      // this.$store.commit("app/updateApiCount", "add");
      getAuditmsg(this.form.id)
        .then((res) => {
          // this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          if (res.data) {
            this.form.latitude = res?.data?.latitude;
            this.form.longitude = res?.data?.longitude;
            this.form.parentId = res?.data?.parentId;
            this.form.message = res?.data?.message;
          }
        })
        .catch((err) => {
          // this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!200391");
        });
    },
    choseDpet(value) {
      this.form.parentId = value;
    },
    getMap(defaultFlage) {
      const that = this;
      // 封装方法，不然要重复写很多次index
      let mapLoad = (value) => {
        return L.tileLayer.chinaProvider(`TianDiTu.${value}`, {
          maxZoom: 18,
          minZoom: 8,
          key: this.mapKey,
        });
      };
      // 定义地图图层，官方api有
      var sateMap = mapLoad("Normal.Map"),
        sateAnnotion = mapLoad("Normal.Annotion");
      var satelliteMap = L.layerGroup([sateMap, sateAnnotion]);
      let map = L.map(this.$refs.mapContainer, {
        center: [29.9872549545339, 122.205], //初始地图中心
        zoom: 11, //初始缩放等级
        maxZoom: 18, //最大缩放等级
        minZoom: 6, //最小缩放等级
        // zoomControl: false,
        attributionControl: false, // 移除右下角leaflet标识
        layers: [satelliteMap], //默认图层展示
      });
      this.map = map;
      const Icon = L.icon({
        iconUrl: that.imgTeye1,
        iconSize: [20, 20], //点大小
      });
      let marker;
      this.map.on("click", function (e) {
        if (marker) that.map.removeLayer(marker);

        marker = L.marker(e.latlng, {
          draggable: false,
          riseOnHover: true,
          icon: Icon,
        }).addTo(that.map);
        that.latlng = e.latlng;
        marker.setLatLng(e.latlng).bindPopup("位置").openPopup();
        that.giveDatatoform(); // 将数据传递给表单
      });
      if (defaultFlage && this.form.latitude && this.form.longitude) {
        let latlng = {
          lat: Number(this.form.latitude),
          lng: Number(this.form.longitude),
        };
        marker = L.marker(latlng, {
          draggable: false,
          riseOnHover: true,
          icon: Icon,
        }).addTo(that.map);
        marker.setLatLng(latlng).bindPopup("初始位置").openPopup();
      }
    },
    giveDatatoform() {
      this.form.latitude = this.latlng.lat.toFixed(7).toString();
      this.form.longitude = this.latlng.lng.toFixed(7).toString();
    },
    chinaLayers(map, url, option) {
      let chinaLeayer = L.tileLayer.chinaProvider(url, option);
      chinaLeayer.addTo(map);
      return chinaLeayer;
    },
    clearLayers() {
      if (this.layers) {
        this.layers.clearLayers();
      }
      // if (this.map) {
      //   this.map = null;
      // }
    },
  },
};
</script>

<style lang="scss" scoped>
.inline-area {
  margin-left: 120px;
}
.inline-area2 {
  margin-left: 62px;
}
.mid-area {
  display: flex;
  align-items: center;
  justify-content: center;
}
.tdtMap {
  margin: 0;
  padding: 0;
  width: 520px;
  height: 300px;
  z-index: 0;
}
</style>
